package org.finesys.common.security.authentication.handler;

import org.finesys.common.core.module.R;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 会话并发处理返回JSON
 */
public class AuthSessionInfomationExpiredStrategy implements SessionInformationExpiredStrategy {
    private final MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();

    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        String message = "该账号已从其他设备登录";
        HttpServletResponse httpServletResponse = event.getResponse();
        ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(httpServletResponse);
        mappingJackson2HttpMessageConverter.write(R.failed(message), MediaType.APPLICATION_JSON, httpResponse);
    }
}
